<template>
    <div>
        <el-card class="box-card">
            <!-- 卡片顶部添加品牌的按钮 -->
            <el-button icon="plus" type="primary" size="default" v-has="`btn.TradeMark.add`" @click="addTrademark">
                添加品牌
            </el-button>
            <!-- 表格组件:用于找展示数据 -->
            <!-- 
                table
                    label 标题
                    border 边框(默认false 设置了就是true)
                    width 设置宽度
                    align 对齐方式
             -->
            <!-- 
                table-colum 默认展示数据使用div
              -->
            <el-table style="margin:10px 0" border :data="trademarkArr">
                <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
                <el-table-column label="品牌名称" align="center">
                    <template #="{ row, $index }">
                        <p>{{ row.tmName }}</p>
                    </template>
                </el-table-column>
                <el-table-column label="品牌的logo" align="center">
                    <template #="{ row, $index }">
                        <img :src="row.logoUrl" alt="" style="width:80px;height: 80px;">
                    </template>
                </el-table-column>
                <el-table-column label="品牌的操作" align="center">
                    <template #="{ row, $index }">
                        <el-button type="primary" size="small" icon="Edit" @click="editTrademark(row)"></el-button>
                        <el-popconfirm :title="`确认删除${row.tmName}?`" width="200px" icon="Delete"
                            @confirm="removeTradeMark(row.id)">
                            <template #reference>
                                <el-button type="primary" size="small" icon="Delete"></el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器
                pagination
                    v-model:current-page:设置分页器当前页码
                    v-model:page-size :每一页的数据条数
                    :page-sizes :用于设置下拉菜单的选项
                    background: 分页器按钮的颜色
                    layout:可以用于调整分页器的子组件的顺序
            -->
            <el-pagination v-model:current-page="pageNo" @current-change="getTradeMark" @size-change="changeSize"
                v-model:page-size="limit" :page-sizes="[3, 5, 7, 9]" layout="prev, pager, next,
                jumper,->, sizes,total " :total="total" />
            <!-- 对话框
                v-model:控制显示和隐藏
                title:设置标题
            -->
            <el-dialog v-model="dialogFormVisable" :title="dialogTitle">
                <el-form :model="trademarkParams" :rules="rules" ref="formRef">
                    <el-form-item label="品牌名称" label-width="100px" prop="tmName">
                        <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
                    </el-form-item>
                    <el-form-item label="品牌logo" label-width="100px" prop="logoUrl">
                        <!-- 上传按钮 -->
                        <!-- upload的属性
                                action  发起上传请求的链接
                        -->
                        <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <!-- 传递一个具名插槽 #footer -->
                <template #footer>
                    <el-button type="primary" size="default" @click="cancel">取消</el-button>
                    <el-button type="primary" size="default" @click="confirm">确定</el-button>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>
<script setup lang='ts'>
import { ref, watch, reactive } from 'vue'
import { reqHasTrademark } from '@/api/product/trademark/index'
import { onMounted, onBeforeUpdate } from 'vue';
import { ElMessage } from 'element-plus';
// import type { } from 'element-plus'
import { reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark/index'
//引入类型
import type { TradeMarkResponseData, Records, TradeMark } from '@/api/product/trademark/type'
//上传文件的类型
import type { UploadProps } from 'element-plus'
import { nextTick } from 'vue';
//当前页码
const pageNo = ref<number>(1)
//单页数据条数
const limit = ref<number>(5)
//存储已有品牌总数
let total = ref<number>(0)
//存储已有品牌数据
let trademarkArr = ref<Records>([])
//控制对话框的显示与隐藏
let dialogFormVisable = ref<boolean>(false)
//获取form组件对象
let formRef = ref();

//定义对话框的标题
let dialogTitle = ref('')

//定义收集品牌数据的对象
let trademarkParams = reactive<TradeMark>({
    tmName: '',
    logoUrl: ''
})

//文件上传时进行限制
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {

    // 该钩子在上传成功之前触发,用于对文件的类型和大小进行限制
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif' || rawFile.type == 'image/png') {
        if (rawFile.size / 1024 / 1024 < 4) {
            return true;
        } else {
            ElMessage({
                type: 'error',
                message: '上传的文件大小不超过4M'
            })
            return false;
        }
    } else {
        ElMessage({
            type: 'error',
            message: '上传的文件格式必须为PNG/JPEG/GIF'
        })
        return false;
    }
}
//上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response: any, uploadFile: any) => {
    //当前请求返回的链接地址
    //手机这个链接数据,在上传新的品牌时带给服务器
    trademarkParams.logoUrl = response.data;

    formRef.value.clearValidate('logoUrl');

}

//添加品牌的按钮的回调
const addTrademark = () => {
    clearTradeMark()
    dialogTitle.value = '添加品牌'
    dialogFormVisable.value = true

    //清除校验提示词 第一种方法,ts的问号语法
    // formRef.value?.clearValidate('tmName');
    // formRef.value?.clearValidate('logoUrl');

    //第二种nextTick
    nextTick(() => {
        formRef.value.clearValidate('tmName');
        formRef.value.clearValidate('logoUrl');
    })
}
//修改品牌的按钮的回调
const editTrademark = (result: TradeMark) => {
    //获取数据
    dialogTitle.value = '修改品牌'
    // trademarkParams.tmName = result.tmName;
    // trademarkParams.logoUrl = result.logoUrl;
    // trademarkParams.id = result.id;

    //采用Es6的合并语法
    Object.assign(trademarkParams, result)
    nextTick(() => {
        formRef.value.clearValidate('tmName');
        formRef.value.clearValidate('logoUrl');
    })
    //显示对话框
    dialogFormVisable.value = true
}
//定义一个获取品牌的函数
const getTradeMark = async (pager = 1) => {
    clearTradeMark();
    pageNo.value = pager
    let result: TradeMarkResponseData = await reqHasTrademark(pageNo.value, limit.value)
    if (result.code === 200) {
        total.value = result.data.total;
        trademarkArr.value = result.data.records;
        total.value = result.data.total
    } else {
        ElMessage({ type: 'error', message: '获取失败' })
    }
}
//页面挂载时发起请求获取数据渲染
onMounted(() => {
    getTradeMark()
})
//清除dialog中的品牌数据
const clearTradeMark = () => {
    trademarkParams.id = undefined
    trademarkParams.tmName = ''
    trademarkParams.logoUrl = ''
}
//对话框 确认
const confirm = async () => {
    //进行确认之前先对表单项进行校验
    //使用await等待校验,当校验不通过时,则后续代码不执行
    await formRef.value.validate();

    let result: any = await reqAddOrUpdateTrademark(trademarkParams)
    //添加成功
    if (result.code == 200) {
        // 关闭对话框
        dialogFormVisable.value = false
        // 进行提示
        ElMessage({ type: 'success', message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功' })
        // 刷新数据
        getTradeMark(trademarkParams.id ? pageNo.value : 1)
        clearTradeMark()
    } else {
        //添加失败
        ElMessage({ type: 'error', message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败' })
        // 关闭对话框
        dialogFormVisable.value = false
        clearTradeMark()
    }
}
//对话框 取消
const cancel = () => {
    dialogFormVisable.value = false;
    clearTradeMark()
}

/**
 * 分页器页码发生变化时会触发 current-change事件,可通过回调函数进行相应的操作(如 数据刷新),该事件会向回调函数注入一个参数,值为当前页面的页码
 * 下拉菜单发生变化时会触发 size-change事件,可通过回调函数进行相应的操作(如 数据刷新),该事件会向回调函数注入一个参数,值为当前下拉菜单中所选择的数值
 */
//改变当前页码刷新数据
const changeSize = () => {
    getTradeMark()
}

//定义品牌名称的校验规则
const validatortmName = (rule: any, value: any, callback: any) => {
    //自定义规则检测
    if (value.trim().length >= 2) {
        callback();
    } else {
        callback(new Error('品牌名称需要大于等于两位'))
    }
}
//定义品牌名称的校验规则
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
    //如果图片上传,则有value
    if (value) {
        callBack()
    } else {
        callBack(new Error('品牌LOGO必须要上传'))
    }
}

//定义校验规则
const rules = {
    logoUrl: [
        { required: true, validator: validatorLogoUrl }
    ],
    tmName: [
        //required 是否必须校验
        { required: true, trigger: 'blur', validator: validatortmName }
    ],
}
//气泡确认框确认对应事件
const removeTradeMark = async (id: number) => {
    let result = await reqDeleteTrademark(id)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: result.message })
        getTradeMark(trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
    } else {
        ElMessage({ type: 'error', message: result.message })
    }
}

</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>